Playing with CSS Variables and JS


Posted by wayne201299 on 2023-09-22

透過JavaScript控制CSS變化
DEMO

  1. 在root中宣告CSS變數
     :root {
       --base: #ffc600;
       --spacing: 10px;
       --blur: 10px;
     }
    
  2. 讓element的吃到變數,以便做動態調整
  3. 監聽input變化
    inputs.forEach(input => input.addEventListener('input', handleUpdate));
    
  4. 每次變化時更新,需要選中CSS變數並更新,document.documentElement取得目前整張文件的HTML element,而root變數就是訂在那一層,因此我們可以直接對其做操作
    function handleUpdate() {
     const suffix = this.dataset.sizing || '';
     document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
    }
    

知識點

  • -- 在CSS標準中代表是變數
  • CSS可以透過var() 取得變數
  • HTML的data-xxx 前綴可以客製想傳入的attribute
  • dataset可以取得所有指定element下的data attribute

補充資料
Document.documentElement-MDN
javascript-dom-attribute-property


#javascript #css







Related Posts

Integration Test on DB-Related Code with Docker Compose

Integration Test on DB-Related Code with Docker Compose

npm 是什麼? yarn 是什麼?

npm 是什麼? yarn 是什麼?

2356. Number of Unique Subjects Taught by Each Teacher

2356. Number of Unique Subjects Taught by Each Teacher


Comments